/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swing.tree;

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;

/**
 *
 * @author Administrator
 */
public class TreeExpandListenerDemo
{

  public static void main(String[] args)
  {
    JFrame frame = new JFrame("treeWillExpandListene..");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
    DefaultMutableTreeNode parent = new DefaultMutableTreeNode("parent");
    parent.add(new DefaultMutableTreeNode("a"));
    root.add(parent);
    root.add(new DefaultMutableTreeNode("A"));
    root.add(new DefaultMutableTreeNode("B"));
    root.add(new DefaultMutableTreeNode("c"));

    JTree tree = new JTree(root);

    TreeWillExpandListener treeWillExpandListener = new TreeWillExpandListener()
    {

      public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException
      {
        TreePath treePath = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent();
        String data = node.getUserObject().toString();
        System.out.println("WillExpand.." + data);
      }

      public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException
      {
        TreePath treePath = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath.getLastPathComponent();
        String data = node.getUserObject().toString();
        System.out.println("WillCollapse.." + data);
      }
    };
    tree.addTreeWillExpandListener(treeWillExpandListener);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 400);
    frame.setVisible(true);
  }
}
